package com.beone.smart.smartBeauty.exception;

import com.beone.smart.smartBeauty.model.result.ResultEntity;
import com.beone.smart.smartBeauty.model.result.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * @author yangjie
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public ResultEntity handException(Exception e) {
        log.error("Exception异常--->{},异常信息为{}", e, getExceptionInfo(e));
        return ResultTool.fail(ResultTool.HttpResponseCode.SERVER_FAIL, e.getMessage());
    }

    @ExceptionHandler(value = GlobalException.class)
    public ResultEntity handException(GlobalException exception) {
        log.error("传入参数异常{},参数--->{}", exception, getExceptionInfo(exception));
        if (exception.getCode() != null) {
            return ResultTool.fail(exception.getCode(), exception.getMessage());
        } else {
            return ResultTool.fail(ResultTool.HttpResponseCode.FAIL, exception.getMessage());
        }
    }

    private String getExceptionInfo(Exception ex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        ex.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
}
